package com.hs.chd.action.data;
 
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.hs.app.service.IDataService;
import com.hs.auth.model.HsAccount;
import com.hs.chd.model.SchdImpfileinfo;
import com.hs.core.action.BaseAction;
import com.hs.core.db.DBMgr;
import com.hs.core.utils.PageParam;
import com.hs.core.utils.PageUtil;
import com.hs.core.utils.SystemUtil;
import com.hs.core.utils.TimeUtil;
@Controller   
public class DataImportController  extends BaseAction {
    private static final Logger logger = Logger.getLogger(DataImportController.class);
	private IDataService dataService;
	@Autowired  
	public void setDataService(IDataService dataService) {
		this.dataService = dataService;
	}
	/**
	  * 数据导入管理界面
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/import/importManage.do" )   
   public ModelAndView pretag(HttpServletRequest request,
		HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException { 
		PageParam pageParam = new PageParam(request,"data/import/importManage.do");
		String mSubject = request.getParameter("filename"); // 题名 
		String datatype = request.getParameter("datatype"); // 题名 
		StringBuffer searchBuffer = new StringBuffer(
				" select a from SchdImpfileinfo a where isdel=1 ");
		PageUtil pageUtil = null;
		
		if (StringUtils.isNotBlank(mSubject)) {
			searchBuffer.append(" and a.filename like '%").append(mSubject).append("%'"); 
			pageParam.getConditionMap().put("filename", mSubject);
			request.setAttribute("filename", mSubject);
		} 
		if (StringUtils.isNotBlank(datatype)&&!"0".equals(datatype)) {
			searchBuffer.append(" and a.datatype =").append(datatype); 
			pageParam.getConditionMap().put("datatype", datatype);
			request.setAttribute("datatype", datatype);
		} 
		searchBuffer.append(" order by a.uploaddate");
		
		 
		pageParam.setSearchSql(searchBuffer.toString());
		pageUtil = dataService.getPageList(pageParam);
		modelMap.put("dataList", pageUtil);  
 		return new ModelAndView("app/data/import/importManage",modelMap);
		 
	 } 
	 /**
	  * 数据文件上传
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/import/datafileUpload.do", method = RequestMethod.GET)   
	 public ModelAndView symtag(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 DBMgr dbo = this.getDbo(request); 
		 return new ModelAndView("app/data/import/datafileUpload",modelMap);
		 
	 } 
	 
	 /**
	  * 数据文件上传
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	 * @throws Exception 
	  */
	 @RequestMapping(value="/data/import/insertDatafile.do")   
     public void executemagaimport(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws Exception {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
		 MultipartFile multipartFile = multipartRequest.getFile("importfile");  
 		 HsAccount curUser = this.getCurrentuser(request); 
 		 String fileName = multipartFile.getOriginalFilename(); 
		 String datatype = request.getParameter("datatype"); 
		 String webRoot = SystemUtil.getWebappRoot().toString();
		 webRoot = webRoot.replace("\\", "/") + "/temp"; 
		 String sep = System.getProperty("file.separator");
		 sep = "/"; 
		 File rootDir = new File(webRoot); 
		 if (!rootDir.exists()) {
			rootDir.mkdirs(); 
		 }
		 String filepath = webRoot + sep + fileName;
		 File file = new File(filepath);
		 BufferedOutputStream bf = new BufferedOutputStream(new FileOutputStream(file));
		 bf.write(multipartFile.getBytes());
		 bf.close();
		 logger.debug("文件"+fileName+"上传成功!"); 
		 //读取文件总行数
	     HSSFWorkbook workbook = null;
	     SchdImpfileinfo impFileInfo = new SchdImpfileinfo();
			try {
				FileInputStream rs = new FileInputStream(file);
				workbook = new HSSFWorkbook(rs); 
//				int total = workbook.getNumberOfSheets(); // 获取sheet个数
				int end = 0;
	 			//for (int i = 0; i < total; i++) {
				HSSFSheet sheet = workbook.getSheetAt(0);// 按索引获取sheet引用 
				end = sheet.getLastRowNum();// sheet起结束行索引
				//} 
				impFileInfo.setFilepath(filepath);
				impFileInfo.setFilename(fileName);
				impFileInfo.setUploaddate(TimeUtil.getCurrentDateTime());
				impFileInfo.setUploaduser(curUser==null?"":curUser.getUserinfo().getUsername());
				impFileInfo.setImpnum(0l);
				impFileInfo.setImpnum(new Long(end));
				impFileInfo.setImpfailpos(0l);
				impFileInfo.setIsdel(1l);
				impFileInfo.setDatatype(new Long(datatype));
				impFileInfo.setImpstatus(1l);
				impFileInfo.setImpcurrnum(0l);
				dataService.save(impFileInfo); 
				
				response.getWriter().write("数据文件上传成功,请执行数据导入操作!");
				response.getWriter().flush();
				response.getWriter().close();

			}catch(Exception e){
				dataService.deleteObject(impFileInfo);
				response.getWriter().write("数据文件上传失败："+e.getMessage());
				response.getWriter().flush();
				response.getWriter().close();
			}
		// HsAccount acc = this.getCurrentuser(request);
		// long userid = acc==null?0l:acc.getId();
		// int  nums[] =  this.importMaga(file,userid,isdouble);
		// response.getWriter().write("导入数据【"+nums[0]+"】条,更新数据【"+nums[1]+"】");
	    // return new ModelAndView("app/data/magaimportview",modelMap);
 		 
	 } 
	 
}
